package com.cheng.sell.service.impl;

import com.cheng.sell.VO.CartVO;
import com.cheng.sell.dao.ProductInfoRepository;
import com.cheng.sell.entity.ProductInfo;
import com.cheng.sell.enums.ProductStatusEnum;
import com.cheng.sell.enums.ResultEnum;
import com.cheng.sell.exception.SellException;
import com.cheng.sell.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * Description:
 * </p>
 *
 * @author chengxintao
 * @version 1.0
 * <p>
 * <p>
 * History:
 * <p>
 * Date                 Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2018/8/21         chengxintao          1.0         To create
 * </p>
 * @see
 * @since
 */
@Service
public class ProductInfoServiceImpl implements ProductInfoService {
    @Autowired
    private ProductInfoRepository productInfoRepository;

    @Override
    public ProductInfo findOne(String productId) {
        return productInfoRepository.findOne(productId);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return productInfoRepository.findAll(pageable);
    }

    @Override
    public ProductInfo save(ProductInfo productInfo) {
        return productInfoRepository.save(productInfo);
    }

    @Override
    public void addStock(List<CartVO> cartVOList) {
        for (CartVO cartVO : cartVOList) {
            ProductInfo productInfo = findOne(cartVO.getProductId());
            if (productInfo == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            Integer stock = productInfo.getProductStock() + cartVO.getProductQuantity();
            productInfo.setProductStock(stock);
        }
    }

    @Override
    @Transactional
    public void decreaseStock(List<CartVO> cartVOList) {
        for (CartVO cartVO : cartVOList) {
            ProductInfo productInfo = findOne(cartVO.getProductId());
            if (productInfo == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            Integer stock = productInfo.getProductStock() - cartVO.getProductQuantity();
            if (stock > 0) {
                productInfo.setProductStock(stock);
            } else {
                throw new SellException(ResultEnum.PRODUCT_NOT_ENOUGH);
            }
        }
    }
}
